﻿using System;
using iTeamyou.LTS.Core.Models;
using System.ComponentModel;
using Newtonsoft.Json;
using AlibabaCloud.SDK.Ocr_api20210707;
using AlibabaCloud.SDK.Ocr_api20210707.Models;
using AlibabaCloud.TeaUtil.Models;
using Spire.Pdf;
using System.Drawing.Imaging;

namespace iTeamyou.LTS.Core.Services
{
	public class AliSupplierLicenseService : IFileService<SupplierLicense, string, string>
    {
        public static Client? client;
        public SharedService _sharedService;
        public bool IsOCREnabled;

        public AliSupplierLicenseService()
        {
            var clientConfig = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = "LTAI5tBbQ5dWF2JgyWKKSAqZ",
                AccessKeySecret = "qZup7iAZIbWJSD58n5mWndWnOwivnK",
                Endpoint = "ocr-api.cn-hangzhou.aliyuncs.com"
            };
            client = new Client(clientConfig);
            _sharedService = new SharedService();
            IsOCREnabled = Convert.ToBoolean(_sharedService.GetConfig("IsOCREnabled"));
        }

        public async Task<SupplierLicense> Get(string input, string type)
        {
            return new SupplierLicense()
            {
                Type = type
            };
        }

        private string ConvertPDFFirstPageToImage(string pdfFullPath)
        {
            var path = pdfFullPath.Substring(0, pdfFullPath.LastIndexOf("\\") + 1);
            var jpgName = $"{Path.GetFileNameWithoutExtension(pdfFullPath)}_{DateTime.Now:yyMMddHHmmss}.jpg";
            var doc = new PdfDocument();
            doc.LoadFromFile(pdfFullPath);
            using var stream = File.Open(Path.Combine(path, jpgName), FileMode.Create);
            using var img = doc.SaveAsImage(1, Spire.Pdf.Graphics.PdfImageType.Bitmap, 300, 300);
            img.Save(stream, ImageFormat.Jpeg);

            return Path.Combine(path, jpgName);
        }
    }

    public class AliProductLicenseService : IFileService<ProductLicense, string, string>
    {
        public static Client? client;
        public List<string> ImageExts = new List<string>() { ".jpg", ".jpeg", ".png", ".bmp" };
        public SharedService _sharedService;
        public bool IsOCREnabled;

        public AliProductLicenseService()
        {
            var clientConfig = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = "LTAI5tBbQ5dWF2JgyWKKSAqZ",
                AccessKeySecret = "qZup7iAZIbWJSD58n5mWndWnOwivnK",
                Endpoint = "ocr-api.cn-hangzhou.aliyuncs.com"
            };
            client = new Client(clientConfig);
            _sharedService = new SharedService();
            IsOCREnabled = Convert.ToBoolean(_sharedService.GetConfig("IsOCREnabled"));
        }

        public async Task<ProductLicense> Get(string input, string type)
        {
            var licenseResult = new ProductLicense() { Type = type };
            if (IsOCREnabled)
            {
                var ext = Path.GetExtension(input).ToLower();
                if (ext == ".pdf")
                    input = ConvertPDFFirstPageToImage(input);

                if (ImageExts.Any(e => e == input))
                {
                    var aliFs = AlibabaCloud.DarabonbaStream.StreamUtil.ReadFromFilePath(input);
                    var runtime = new RuntimeOptions();
                    try
                    {
                        switch (type)
                        {
                            case "Barcode":
                                var request = new RecognizeAdvancedRequest
                                {
                                    Body = aliFs,
                                    NoStamp = true,
                                    Row = true,
                                    NeedSortPage = true,
                                    OutputTable = true
                                };
                                var response = client.RecognizeAdvancedWithOptions(request, runtime);
                                var result = JsonConvert.DeserializeObject<AliRecognizeData>(response.Body.Data);
                                break;
                            case "DomesticOrdinaryCosmetics":
                                break;
                            case "DomesticSpecialCosmetics":
                                break;
                            case "ImportOrdinaryCosmetics":
                                break;
                            case "CustomsDeclaration":
                                break;
                            case "ImportSpecialCosmetics":
                                break;
                            case "ImportQuarantine":
                                break;
                            default:
                                break;
                        }
                    }
                    catch { throw; }
                }
            }

            return licenseResult;
        }

        private string ConvertPDFFirstPageToImage(string pdfFullPath)
        {
            var path = pdfFullPath.Substring(0, pdfFullPath.LastIndexOf("\\") + 1);
            var jpgName = $"{Path.GetFileNameWithoutExtension(pdfFullPath)}_{DateTime.Now:yyMMddHHmmss}.jpg";
            var doc = new PdfDocument();
            doc.LoadFromFile(pdfFullPath);
            using var stream = File.Open(Path.Combine(path, jpgName), FileMode.Create);
            using var img = doc.SaveAsImage(0, Spire.Pdf.Graphics.PdfImageType.Bitmap, 300, 300);
            img.Save(stream, ImageFormat.Jpeg);

            return Path.Combine(path, jpgName);
        }
    }

    public class AliManufacturerLicenseService : IFileService<ManufacturerLicense, string, string>
    {
        public static Client? client;
        public SharedService _sharedService;
        public bool IsOCREnabled;

        public AliManufacturerLicenseService()
        {
            var clientConfig = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = "LTAI5tBbQ5dWF2JgyWKKSAqZ",
                AccessKeySecret = "qZup7iAZIbWJSD58n5mWndWnOwivnK",
                Endpoint = "ocr-api.cn-hangzhou.aliyuncs.com"
            };
            client = new Client(clientConfig);
            _sharedService = new SharedService();
            IsOCREnabled = Convert.ToBoolean(_sharedService.GetConfig("IsOCREnabled"));
        }

        public async Task<ManufacturerLicense> Get(string input, string type)
        {
            return new ManufacturerLicense()
            {
                Type = type
            };
        }
    }

    public class AliBatchLicenseService : IFileService<BatchLicense, string, string>
    {
        public static Client? client;
        public SharedService _sharedService;
        public bool IsOCREnabled;

        public AliBatchLicenseService()
        {
            var clientConfig = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = "LTAI5tBbQ5dWF2JgyWKKSAqZ",
                AccessKeySecret = "qZup7iAZIbWJSD58n5mWndWnOwivnK",
                Endpoint = "ocr-api.cn-hangzhou.aliyuncs.com"
            };
            client = new Client(clientConfig);
            _sharedService = new SharedService();
            IsOCREnabled = Convert.ToBoolean(_sharedService.GetConfig("IsOCREnabled"));
        }

        public async Task<BatchLicense> Get(string input, string type)
        {
            return new BatchLicense()
            {
                Type = type
            };
        }
    }
}

